package com.yfp.device.utils;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

/**
 * 阿里云-oss
 *
 *
 * @date 2023/12/04
 */
@Service
@Slf4j
public class OssServiceImpl {

    private static AliyunOssConfig aliyunOssConfig;

    /**
     * 使用构造方法注入配置信息
     */
    @Autowired
    public OssServiceImpl(AliyunOssConfig aliyunOssConfig) {
        OssServiceImpl.aliyunOssConfig = aliyunOssConfig;
    }

    public OssFile uploadFile(MultipartFile file) throws Exception {
        OssFile ossFile = new OssFile();
        // 生成 OSSClient
        OSS ossClient = new OSSClientBuilder().build(aliyunOssConfig.getEndpoint(), aliyunOssConfig.getAccessKeyId(), aliyunOssConfig.getAccessKeySecret());
        // 原始文件名称
        String originalFilename = file.getOriginalFilename();

        // 编码文件名
        String filePathName = FileUploadUtils.extractFilename(file);
        // 文件路径名称
        filePathName = aliyunOssConfig.getFilehost() + "/" + filePathName;
        try {
            ossClient.putObject(aliyunOssConfig.getBucketName(), filePathName, file.getInputStream());
            ossFile.setFileName(originalFilename);
            ossFile.setUrl(aliyunOssConfig.getUrl() + "/" + filePathName);
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
        return ossFile;
    }
}
